import random

from django.http import JsonResponse, HttpResponse
from django.views import View

from celery_tasks.sms.tasks import send_sms_code
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection

from libs.yuntongxun.sms import CCP
import logging
logger = logging.getLogger('django')


class ImageCodeView(View):

    def get(self, request, uuid):
        """
        生成验证码
        :param request:
        :param uuid:
        :return:
        """
        # 1.生成图片验证码和图片二进制
        text, image = captcha.generate_captcha()

        # 2.通过redis把图片验证码保存起来
        # 2.1 进行redis的连接
        redis_conn = get_redis_connection('code')
        # 2.2 指令操作
        redis_conn.setex('img_%s' % uuid, 300, text)

        # 3.返回图片二进制
        return HttpResponse(image, content_type='image/jpeg')


class SmsCodeView(View):

    def get(self, request, mobile):
        # 获取请求参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        # 验证参数
        if not all([image_code_client, uuid]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数！'})

        # 创建连接到redis的对象
        redis_conn = get_redis_connection('code')
        # 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            # 图形验证码过期或者不存在
            return JsonResponse({'code': 400, 'errmsg': '图形验证码失效！'})
        # 删除图形验证码，避免恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)
        # 对比图片验证码
        image_code_server = image_code_server.decode()  # bytes转字符
        if image_code_client.lower() != image_code_server.lower():
            return JsonResponse({'code': 400, 'errmsg': '图形验证码错误！'})

        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return JsonResponse({'code': 400, 'errmsg': '发送短信过于频繁'})

        # 生成短信验证码：生成4位数验证码
        sms_code = '%04d' % random.randint(0, 9999)
        logger.info(sms_code)

        # 保存短信验证码
        # redis_conn.setex('sms_%s' % mobile, 300, sms_code)
        # 写入send_flag
        # redis_conn.setex('sms_%s' % mobile, 300, sms_code)

        # 管道 3 步
        # 新建一个管道
        pipeline = redis_conn.pipeline()
        # 管道收集指令
        pipeline.setex('sms_%s' % mobile, 300, sms_code)
        pipeline.setex('sms_%s' % mobile, 300, sms_code)
        # 管道执行指令
        pipeline.execute()
        
        # 发送短信验证码
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, 5], 1)

        # delay的参数等同于任务的参数
        send_sms_code.delay(mobile, sms_code)

        # 响应结果
        return JsonResponse({'code': 0, 'errmsg': '发送短信验证码成功！'})
